package com.itcast.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.itcast.pojo.Result;
import com.itcast.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LibraryInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求token，不为空，进行下一步
        String token = request.getHeader("token");
        if (!StringUtils.hasLength(token)) {
            Result result = Result.error("NOT_LOGIN");
            String s = JSONObject.toJSONString(result);
            response.getWriter().write(s);
            response.setContentType("application/json;charset=UTF-8");
            return false;
        }
        //解析token，正确放行
        try {
            JwtUtils.parseJWT(token);
        } catch (Exception e) {
            Result result = Result.error("NOT_LOGIN");
            String s = JSONObject.toJSONString(result);
            response.getWriter().write(s);
            response.setContentType("application/json;charset=UTF-8");
            return false;
        }
        return true;
    }
}
